import request from '@/utils/request'

export default {
  data() {
    return {
      loopTimer: null,
    }
  },
  mounted() {
    if(!this.curComp) return
    this.sendRequest()
  },
  destroyed() {
    if(this.loopTimer) {
      clearInterval(this.loopTimer)
      this.loopTimer = null
    }
  },
  methods: {
    sendRequest() {
      const { server } = this.curComp
      if(server.dataType == '1' && server.config.url) {
        requestHandler(server)
        if(server.isLoop) {
          this.loopTimer = setInterval(() => {
            requestHandler(server)
          }, server.loopTime * 1000)
        }
      }
    },
    requestHandler(server) {
      let url = server.config.url
      let method = server.config.method
      let headers = this.getOptions(server.config.headers)
      let params = this.getOptions(server.config.params)
      let data = this.getOptions(server.config.body)
      request({ url, method, headers, params, data }).then(res => {
        const func = new Function('res', server.logic)
        this.curComp.data = func.call(this, res)
      })
    },
    getOptions(data) {
      const target = {}
      data.forEach(item => {
        try {
          target[item.key] = JSON.parse(item.value)
          if(typeof target[item.key] !== 'object') {
            target[item.key] = String(target[item.key])
          }
        }catch(e) {
          target[item.key] = item.value
        }
      })
      return target
    }
  }
}